﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections;
using System.Runtime.InteropServices;
using System.IO;
using System.Net;
using System.Security.Permissions;
using System.DirectoryServices;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace ConnectLib
{
    public class Functions
    {        
        public Functions()
        {
            
        }

        public static long GenerateUniqueID()
        {
            DateTime dt2010 = new DateTime(2010, 1, 1, 0, 0, 1);
            TimeSpan deltaDay;
            deltaDay = DateTime.UtcNow - dt2010;
            long totalMiliseconds = (long)deltaDay.TotalMilliseconds;

            //sinh ra mot chuoi Guid
            //lay 4 ky tu dau tien trong nhom 2
            //chuyen sang so Int -> radomNumder
            //UniqueID= totalMiliseconds * 10000 + randomNumber/10
            string guid = Guid.NewGuid().ToString();
            string pattern = "^\\w+-(?<guid>\\w+)-";//936DA01F-9ABD-4d9d-80C7-02AF85C822A8
            Regex rg = new Regex(pattern);
            Match m = rg.Match(guid);
            string v = m.Groups["guid"].Value;
            int randomNumber = int.Parse(v, System.Globalization.NumberStyles.HexNumber);
            //
            long uniqueID = totalMiliseconds * 10000 + randomNumber / 10;
            return uniqueID;
        }
        public static string writeTime(DateTime mydate) 
        {
            var year = mydate.Year;
            if (year < 1000)
                year += 1900;

            var month = mydate.Month.ToString();
            if (mydate.Month < 10)
                month = "0" + month;
            var day = mydate.Day.ToString();
            if (mydate.Day < 10)
                day = "0" + day;

            int dayw = Convert.ToInt32(mydate.DayOfWeek); 

            var hour = mydate.Hour.ToString();
            if (mydate.Hour < 10)
                hour = "0" + hour;

            var minute = mydate.Minute.ToString();
            if (mydate.Minute < 10)
                minute = "0" + minute;

            string[] dayArray = new string[] { "Chủ Nhật", "Thứ Hai", "Thứ Ba", "Thứ Tư", "Thứ Năm", "Thứ Sáu", "Thứ Bảy" };
            string strDay = dayArray[dayw] + ", " + day + "/" + month + "/" + year + ", " + hour + ":" + minute + " (GMT+7)";
             return strDay;
        }
    }

    public class ImageProcess
    {
        public static System.Drawing.Image ResizeImageToThumbnail(System.Drawing.Image original_image, int target_width, int target_height, Color bkColor)
        {
            System.Drawing.Bitmap final_image = null;
            System.Drawing.Graphics graphic = null;
            MemoryStream ms = null;

            try
            {
                // Calculate the new width and height
                int width = original_image.Width;
                int height = original_image.Height;

                int new_width, new_height;

                float target_ratio = (float)target_width / (float)target_height;
                float image_ratio = (float)width / (float)height;

                if (target_ratio > image_ratio)
                {
                    new_height = target_height;
                    new_width = (int)Math.Floor(image_ratio * (float)target_height);
                }
                else
                {
                    new_height = (int)Math.Floor((float)target_width / image_ratio);
                    new_width = target_width;
                }

                new_width = new_width > target_width ? target_width : new_width;
                new_height = new_height > target_height ? target_height : new_height;


                final_image = new System.Drawing.Bitmap(target_width, target_height);
                graphic = System.Drawing.Graphics.FromImage(final_image);
                graphic.FillRectangle(new System.Drawing.SolidBrush(bkColor), new System.Drawing.Rectangle(0, 0, target_width, target_height));
                int paste_x = (target_width - new_width) / 2;
                int paste_y = (target_height - new_height) / 2;
                graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */

                graphic.DrawImage(original_image, paste_x, paste_y, new_width, new_height);

                // Store the thumbnail in the session (Note: this is bad, it will take a lot of memory, but this is just a demo)
                ms = new MemoryStream();
                final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch
            {
                // Clean up
                if (final_image != null) final_image.Dispose();
                if (graphic != null) graphic.Dispose();
                if (original_image != null) original_image.Dispose();
                if (ms != null) ms.Close();
            }
            finally
            {
                // Clean up
                if (graphic != null) graphic.Dispose();
                if (original_image != null) original_image.Dispose();
                if (ms != null) ms.Close();

            }

            return final_image;
        }

        public static System.Drawing.Image ResizeImageToThumbnail(System.Drawing.Image original_image, int target_width, int target_height)
        {
            System.Drawing.Bitmap final_image = null;
            System.Drawing.Graphics graphic = null;
            MemoryStream ms = null;

            try
            {
                // Calculate the new width and height
                int width = original_image.Width;
                int height = original_image.Height;

                int new_width, new_height;

                float target_ratio = (float)target_width / (float)target_height;
                float image_ratio = (float)width / (float)height;

                if (target_ratio > image_ratio)
                {
                    new_height = target_height;
                    new_width = (int)Math.Floor(image_ratio * (float)target_height);
                }
                else
                {
                    new_height = (int)Math.Floor((float)target_width / image_ratio);
                    new_width = target_width;
                }

                new_width = new_width > target_width ? target_width : new_width;
                new_height = new_height > target_height ? target_height : new_height;


                final_image = new System.Drawing.Bitmap(target_width, target_height);
                graphic = System.Drawing.Graphics.FromImage(final_image);
                graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.White), new System.Drawing.Rectangle(0, 0, target_width, target_height));
                int paste_x = (target_width - new_width) / 2;
                int paste_y = (target_height - new_height) / 2;
                graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */

                graphic.DrawImage(original_image, paste_x, paste_y, new_width, new_height);

                // Store the thumbnail in the session (Note: this is bad, it will take a lot of memory, but this is just a demo)
                ms = new MemoryStream();
                final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch
            {
                // Clean up
                if (final_image != null) final_image.Dispose();
                if (graphic != null) graphic.Dispose();
                if (original_image != null) original_image.Dispose();
                if (ms != null) ms.Close();
            }
            finally
            {
                // Clean up
                if (graphic != null) graphic.Dispose();
                if (original_image != null) original_image.Dispose();
                if (ms != null) ms.Close();

            }

            return final_image;
        }

        public static byte[] ResizeImageToThumbnail(byte[] imageData, int target_width, int target_height)
        {
            try
            {
                MemoryStream ms = new MemoryStream(imageData);
                System.Drawing.Image originalImage = null;
                try
                {
                    originalImage = System.Drawing.Image.FromStream(ms);
                }
                catch (Exception ex1)
                {
                    ms.Close(); ms.Dispose();
                    //Global.writeFile(ErrorType.HandleError, ex1.Message + "\n" + ex1.StackTrace);
                    return null;
                }
                int width = originalImage.Width;
                int height = originalImage.Height;

                int new_width, new_height;

                float target_ratio = (float)target_width / (float)target_height;
                float image_ratio = (float)width / (float)height;

                if (target_ratio > image_ratio)
                {
                    new_height = target_height;
                    new_width = (int)Math.Floor(image_ratio * (float)target_height);
                }
                else
                {
                    new_height = (int)Math.Floor((float)target_width / image_ratio);
                    new_width = target_width;
                }

                new_width = new_width > target_width ? target_width : new_width;
                new_height = new_height > target_height ? target_height : new_height;
                Image thumbImage = new System.Drawing.Bitmap(new_width + 4, new_height + 4);


                int paste_x = (target_width - new_width) / 2;
                int paste_y = (target_height - new_height) / 2;

                using (Graphics graphic = Graphics.FromImage(thumbImage))
                {
                    graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.White),
                            new System.Drawing.Rectangle(0, 0, new_width + 4, new_height + 4));
                    graphic.DrawImage(originalImage, 2, 2, new_width, new_height);
                    if (graphic != null)
                        graphic.Dispose();
                }
                if (ms != null)
                {
                    ms.Close(); ms.Dispose();
                }
                if (originalImage != null)
                    originalImage.Dispose();
                MemoryStream ms2 = new MemoryStream();
                thumbImage.Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] outByteArr = ms2.ToArray();
                if (ms2 != null)
                {
                    ms2.Close(); ms2.Dispose();
                }
                return outByteArr;
            }
            catch (Exception ex)
            {
                //Global.writeFile(ErrorType.HandleError, ex.Message + "\n" + ex.StackTrace);
                return null;
            }

        }

        public static bool IsExtenImageFile(string extFile)
        {
            try
            {
                extFile = extFile.ToLower();
                if ((extFile == ".jpg") ||
                    (extFile == ".jpeg") ||
                    (extFile == ".gif") ||
                    (extFile == ".bmp") ||
                    (extFile == ".png") ||
                    (extFile == ".img") ||
                    (extFile == ".jpe") ||
                    (extFile == ".jfjf") ||
                    (extFile == ".tif") ||
                    (extFile == ".tiff") ||
                     (extFile == ".dib")
                    )

                    return true;
                return false;
            }
            catch (Exception ex)
            {
                //Global.writeFile(ErrorType.HandleError, ex.Message + "\n" + ex.StackTrace);// ghi xuong file text de theo doi loi sai.
                return false;
            }
        }

        public static byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = null;
            try
            {
                ms = new MemoryStream();
                imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                return ms.ToArray();
            }
            catch (Exception ex)
            {
                if (ms != null)
                {
                    ms.Close();
                    ms.Dispose();
                }
                throw ex;
            }
        }

        public static Image byteArrayToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = null;
            try
            {
                ms = new MemoryStream(byteArrayIn);
                Image returnImage = Image.FromStream(ms);
                return returnImage;
            }
            catch (Exception ex)
            {
                if (ms != null)
                {
                    ms.Close();
                    ms.Dispose();
                }
                throw ex;
            }
        }
        public static void SaveJpeg(string path, Image img, int quality)
        {
            try
            {
                if (quality < 0 || quality > 100)
                    throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");


                // Encoder parameter for image quality 
                EncoderParameter qualityParam =
                    new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                // Jpeg image codec 
                ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;

                img.Save(path, jpegCodec, encoderParams);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void SaveJpeg(string path, byte[] imageByte, int quality)
        {
            Image img = null;
            try
            {
                if (quality < 0 || quality > 100)
                    throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");


                // Encoder parameter for image quality 
                EncoderParameter qualityParam =
                    new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                // Jpeg image codec 
                ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;

                img = byteArrayToImage(imageByte);

                img.Save(path, jpegCodec, encoderParams);

                img.Dispose();
            }
            catch (Exception ex)
            {
                if (img != null)
                    img.Dispose();
                throw ex;
            }
        }

        /// <summary> 
        /// Returns the image codec with the given mime type 
        /// </summary> 
        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats 
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec 
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }
    }
}